
import notification from 'utils/notification';
import util from 'utils/util';
//引入接口
import sysRoleApi from "api/sysRoleApi";
import sysMenuApi from "api/sysMenuApi";
import sysFunctionApi from "api/sysFunctionApi";
const { queryDataList, sysRoleAdd, sysRoleEdit, sysRoleDel, querySysRoleById, queryMenuByRoleId, setRoleMenu,queryFunctionByRoleId,setRoleFunction } = sysRoleApi;
const { queryTreeList } = sysMenuApi;
export default {
    namespace: 'sysRoleModel',
    state: {
        addShowVisible: false,
        editShowVisible: false,
        detailShowVisible: false,
        tabledata: {
            datalist: [],
            totalSize: 0
        },
        queryParams: {},
        detailData: {},
        editData: {},
        pageSize: 10,
        page: 1,
        menuTreeData: [],
        funcitonAllData: []
    },
    effects: {
        /**
          * 初始化页面
          */
        *initPageData({ payload, callback }, { select, call, put }) {
            //写入数据
            yield put({
                type: 'updateState',
                payload: {
                    pageSize: 10, page: 1, queryParams: {}, tabledata: {
                        datalist: [],
                        totalSize: 0
                    },
                    addShowVisible: false,
                    editShowVisible: false,
                    detailShowVisible: false
                },
            });
            //获取数据
            yield put({
                type: 'querylist',
                payload: {}
            });
            //菜单树形结构
            yield put({
                type: 'queryTreeList',
                payload: {}
            });

            //功能列表
            yield put({
                type: 'queryFunctionList',
                payload: {}
            });

        },
        /**
          * 刷新页面
          */
        *refreshPageData({ payload, callback }, { select, call, put }) {
            yield put({
                type: 'updateState',
                payload: {
                    addShowVisible: false,
                    editShowVisible: false,
                    detailShowVisible: false
                },
            });
            //获取数据
            yield put({
                type: 'querylist',
                payload: {}
            });
        },
        /**
          * 查询列表
          */
        *querylist({ payload, callback }, { select, call, put }) {
            //获取搜索条件
            const { queryParams, pageSize, page } = yield select(_ => _.sysRoleModel);
            let rs = yield call(queryDataList, { pageSize, page, queryParams });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                //请求成功
                let datalist = rs.data.tabledata.datalist;
                let totalSize = rs.data.tabledata.datalist;
                if (datalist.length == 0 && page > 1) {
                    //再次请求数据
                    yield put({
                        type: 'pageOrPageSizeChange',
                        payload: { pageSize, page: Math.ceil(totalSize / pageSize) },
                    });
                } else {
                    //写入数据
                    yield put({
                        type: 'updateState',
                        payload: { "tabledata": rs.data.tabledata },
                    });
                }
            }
        },

        *pageOrPageSizeChange({ payload }, { call, put }) {
            //更新页面大小，当前页数据
            yield put({
                type: 'updateState',
                payload: { pageSize: payload.pageSize, page: payload.page }
            });
            //重新获取列表数据
            yield put({
                type: 'refreshPageData',
                payload: {}
            });
        },

        *querySubmit({ payload }, { call, put }) {
            //设置搜索内容，page设置为1
            yield put({
                type: 'updateState',
                payload: { queryParams: payload.queryParams, page: 1 }
            });
            //重新获取列表数据
            yield put({
                type: 'querylist',
                payload: {}
            });
        },
        *addShow({ payload, callback }, { call, put }) {
            yield put({
                type: 'updateState',
                payload: { addShowVisible: true }
            });
        },
        *editShow({ payload, callback }, { call, put }) {
            let rs = yield call(querySysRoleById, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                yield put({
                    type: 'updateState',
                    payload: { editShowVisible: true, editData: rs.data }
                });
            }
        },
        *detailShow({ payload, callback }, { call, put }) {
            let rs = yield call(querySysRoleById, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                yield put({
                    type: 'updateState',
                    payload: { detailShowVisible: true, detailData: rs.data }
                });
            }
        },
        *addRowData({ payload, callback }, { call, put }) {
            //构建数据提交到服务器
            let rs = yield call(sysRoleAdd, payload.subData);
            if (util.verifyErrCode(rs.code, "保存成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
                //回调清空表单
                callback({ code: rs.code });
            }
        },
        *editRowData({ payload, callback }, { call, put }) {
            //构建数据提交到服务器
            let rs = yield call(sysRoleEdit, payload.subData);
            if (util.verifyErrCode(rs.code, "编辑并保存成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
                //回调清空表单
                callback({ code: rs.code });
            }
        },
        *delRowData({ payload, callback }, { call, put }) {
            let rs = yield call(sysRoleDel, payload);
            if (util.verifyErrCode(rs.code, "删除成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
            }
        },
        *queryTreeList({ payload, callback }, { call, put }) {
            let rs = yield call(queryTreeList, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                // let menuTreeData = genTreeList(rs.data.menuTreeData, "");
                let menuTreeData = toTreeList(rs.data.menuTreeData, "menu_id", "parent_id", [["title", "menu_name"], ["value", "menu_id"], ["key", "menu_id"]]);

                yield put({
                    type: 'updateState',
                    payload: { menuTreeData }
                });
            }
        },
        *queryMenuByRoleId({ payload, callback }, { call, put }) {
            let rs = yield call(queryMenuByRoleId, { role_id: payload.role_id });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                let retkeys = [];
                let retdata = rs.data;
                for (var i = 0; i < retdata.length; i++) {
                    retkeys.push(retdata[i].menu_id);
                }
                callback(retkeys);
            }
        },
        *setRoleMenu({ payload, callback }, { call, put }) {
            let rs = yield call(setRoleMenu, { role_id: payload.role_id, menus: payload.menus });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                callback(rs.data);
            }
        },
        *queryFunctionList({ payload, callback }, { call, put }) {
            let rs = yield call(sysFunctionApi.queryDataList, { isAll: true });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                // let menuTreeData = genTreeList(rs.data.menuTreeData, "");
                let funcitonAllData = rs.data || [];
                //格式一下数据
                for (var i = 0; i < funcitonAllData.length; i++) {
                    funcitonAllData[i].key = funcitonAllData[i].function_id;
                    funcitonAllData[i].title = funcitonAllData[i].function_name;
                }
                yield put({
                    type: 'updateState',
                    payload: { funcitonAllData }
                });
            }
        },
        *queryFunctionByRoleId({ payload, callback }, { call, put }) {
            let rs = yield call(queryFunctionByRoleId, { role_id: payload.role_id });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                let retkeys = [];
                let retdata = rs.data;
                for (var i = 0; i < retdata.length; i++) {
                    retkeys.push(retdata[i].function_id);
                }
                callback(retkeys);
            }
        },
        *setRoleFunction({ payload, callback }, { call, put }) {
            let rs = yield call(setRoleFunction, { role_id: payload.role_id, functions: payload.functions });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                callback(rs.data);
            }
        },
    },

    reducers: {
        updateState(state, { payload }) {
            return {
                ...state,
                ...payload,
            }
        },
    }
}

function toTreeList(data, primary_key, parent_key, mapkey) {
    let result = [];

    //检验数据是否符合规范
    if (!Array.isArray(data) || (!primary_key) || (!parent_key)) {
        return result
    }
    //键值映射关系
    if (!Array.isArray(mapkey)) {
        mapkey = [];
    }

    data.forEach(item => {
        delete item.children;
    });
    let map = {};
    data.forEach(item => {
        map[item[primary_key]] = item;
    });
    data.forEach(item => {
        let parent = map[item[parent_key]];
        //关系映射
        for (var i = 0; i < mapkey.length; i++) {
            let mapItem = mapkey[i];
            //锁定映射关系是否合法
            if (Array.isArray(mapItem)) {
                if (mapItem.length == 2) {
                    item[mapItem[0]] = item[mapItem[1]];
                }
            }
        }
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}
